<?php

namespace App\Http\Controllers\api;

use App\Constant\Enum;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserWalletActive;

class UserWalletController extends BaseController
{
    private $columns = ['id', 'user_id', 'user_withdraw_id', 'wallet_type', 'action', 'coins', 'status', 'changed_at'];

    // 收入
    public function incomes()
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $list = UserWalletActive::query()
            ->select($this->columns)
            ->where('action', Enum::WALLET_ACTIVE_ACTION_INCOME)
            ->where('user_id', $user['id'])
            ->latest()
            ->get();

        $totalIncome = UserWalletActive::query()
            ->where('action', Enum::WALLET_ACTIVE_ACTION_INCOME)
            ->where('user_id', $user['id'])
            ->where('status', Enum::WALLET_ACTIVE_STATUS_APPROVED)
            ->sum('coins');

        foreach ($list as &$item) {
            $item->status_lable = Enum::getWithdrawStatusExplain($item->status ?? '');
        }

        return $this->success([
            'total' => sprintf("%.2f", $totalIncome / Setting::get('exchange_rate')),
            'list' => $list,
        ]);
    }

    // 支出
    public function outcomes()
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $list = UserWalletActive::query()
            ->with([
                'withdraw:id,remark'
            ])
            ->select($this->columns)
            ->where('action', Enum::WALLET_ACTIVE_ACTION_OUTCOME)
            ->where('user_id', $user['id'])
            ->latest()
            ->get();

        $totalOutcome = UserWalletActive::query()
            ->where('action', Enum::WALLET_ACTIVE_ACTION_OUTCOME)
            ->where('user_id', $user['id'])
            ->where('status', Enum::WALLET_ACTIVE_STATUS_APPROVED)
            ->sum('coins');

        foreach ($list as &$item) {
            $item->status_lable = Enum::getWithdrawStatusExplain($item->status ?? '');
            if ($item->status == Enum::WALLET_ACTIVE_STATUS_REJECT) {
                $item->withdraw_lable = $item->withdraw ? ($item->withdraw->remark ?? '--') : '--';
                if (empty($item->withdraw_lable)) {
                    $item->status_lable = $item->withdraw_lable;
                }
            } else {
                $item->withdraw_lable = "";
            }

            unset($item->withdraw);
        }

        return $this->success([
            'total' => sprintf("%.2f", $totalOutcome / Setting::get('exchange_rate')),
            'list' => $list,
        ]);
    }
}
